#include "McGuireMutex.h"

McGuireMutex::McGuireMutex(Resource* r)
{
	resource = r;
	currentOwner = ResourceManager::registerResource(r);
	mutexUsers = ResourceManager::getResourceUsers(r);
	userStates = ResourceManager::registerResourceUser(r, 

}
void McGuireMutex::lock()
{
	i = 0;
	for(i = 0; i < share.processMap.size(); i++)
		if(share.processMap.get(i)==processID)
			break;
	//I have the right index now.
	do
	{

		share.flags.set(i, WAITING);
		index = share.turn;
		while(index != i)
		{
			if(share.flags.get(index) != IDLE) 
				index = turn;
			else
				index = (index + 1) % share.flags.size();
		}

		share.flags.set(i, ACTIVE);

		index = 0;
		while((index < share.flags.size()) && ((index == i)
			|| (share.flags.get(index) != ACTIVE)))
		{
			index = index + 1;
		}
	}
	while(!((index >= share.flags.size()) && ((turn == i) 
		|| (share.flags.get(turn) == IDLE))));

	//claim the turn now
	share.turn = i;
}

void McGuireMutex::unlock()
{
	index = share.turn + 1 % share.flags.size();
	while(share.flags.get(index) == IDLE)
	{
		index = (index + 1) % share.flags.size();
	}
	share.turn = index;
	share.flags.set(i, IDLE);
}



